#ifndef __M_SERVER_H__
#define __M_SERVER_H__

#include "db.hpp"
#include "matcher.hpp"
#include "online.hpp"
#include "room.hpp"
#include "session.hpp"
#include "util.hpp"

#define WWWROOT "./wwwroot/"

class gobang_server
{
private:
    // 静态资源请求处理
    void file_handler(wsserver_t::connection_ptr& conn)
    {
        // 获取uri，并拼出实际路径
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        std::string pathname =_web_root + uri;
        if (pathname.back() == '/') pathname += "login.html"; // 请求目录则返回登录界面
        Json::Value resp_json;
        std::string body;
        bool ret = file_util::read(pathname, body);
        if (ret == false)
        {
            body += "<html>";
            body += "<head>";
            body += "<meta charset='UTF-8'/>";
            body += "</head>";
            body += "<body>";
            body += "<h1> Not Found </h1>";
            body += "</body>";
            conn->set_status(websocketpp::http::status_code::not_found);
            conn->set_body(body);
            return;
        }
        conn->set_body(body);
        conn->set_status(websocketpp::http::status_code::ok);
    }
    // http应答
    // 在调用websocketpp的http回调函数后会自动send
    void http_resp(wsserver_t::connection_ptr& conn, bool result, 
        websocketpp::http::status_code::value code, const std::string& reason)
    {
        Json::Value resp_json;
        resp_json["result"] = result;
        resp_json["reason"] = reason;
        std::string resp_body;
        json_util::serialize(resp_json, resp_body);
        conn->set_status(code);
        conn->set_body(resp_body);
        conn->append_header("Content-Type", "application/json");
    }
    // 用户注册功能请求处理
    void reg(wsserver_t::connection_ptr& conn)
    {
        // 获取请求正文，反序列化得到用户名和密码
        websocketpp::http::parser::request req = conn->get_request();
        std::string req_body = conn->get_request_body();
        Json::Value login_info;
        bool ret = json_util::unserialize(req_body, login_info);
        if (ret == false)
        {
            DLOG("反序列化注册信息失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请求的格式错误!");
        }
        // 在数据库中进行新增操作
        if (login_info["username"].isNull() || login_info["password"].isNull())
        {
            DLOG("用户名密码不完整！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名或密码！");
        }
        ret = _ut.insert(login_info);
        if (ret == false)
        {
            DLOG("数据库插入数据失败");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名已被占用！");
        }
        // 成功，返回200
        http_resp(conn, true, websocketpp::http::status_code::ok, "注册成功！");
    }
    // 用户登录功能请求处理
    void login(wsserver_t::connection_ptr& conn)
    {
        // 获取请求正文，反序列化得到用户和密码
        std::string req_body = conn->get_request_body();
        Json::Value login_info;
        bool ret = json_util::unserialize(req_body, login_info);
        if (ret == false)
        {
            DLOG("反序列化登录信息失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请求的格式错误!");
        }
        // 校验数据库信息是否存在
        if (login_info["username"].isNull() || login_info["password"].isNull())
        {
            DLOG("用户名密码不完整！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名或密码！");
        }
        ret = _ut.login(login_info);
        if (ret == false)
        {
            DLOG("用户名密码错误！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名密码错误！");
        }
        // 验证成功，给客户端创建session
        uint64_t uid = login_info["id"].asUInt64();
        session_ptr ssp = _sm.create_session(uid, LOGIN);
        if (ssp.get() == nullptr)
        {
            DLOG("创建会话失败！");
            return http_resp(conn, false, websocketpp::http::status_code::internal_server_error, "创建会话失败！");
        }
        _sm.set_session_expire_time(ssp->ssid(), SESSION_TIMEOUT);
        // 设置响应头部：Set-Cookie，将ssid通过cookie返回
        std::string cookie_ssid = "SSID=" + std::to_string(ssp->ssid());
        conn->append_header("Set-Cookie", cookie_ssid);
        http_resp(conn, true, websocketpp::http::status_code::ok, "登录成功！");
    }
    // 已"; "为分隔符来取出ssid   Cookie: SSID=XXX; path=/
    bool get_cookie_val(const std::string& cookie_str, const std::string& key, std::string& val)
    {
        std::string sep = "; ";
        std::vector<std::string> cookie_arr;
        string_util::split(cookie_str, sep, cookie_arr);
        for (auto str : cookie_arr)
        {
            // 再根据"="进行分割
            std::vector<std::string> vs;
            string_util::split(str, "=", vs);
            if (vs.size() != 2) continue;
            if (vs[0] == key)
            {
                val = vs[1];
                return true;
            }
        }
        return false;
    }
    // 用户信息获取功能请求处理
    void info(wsserver_t::connection_ptr& conn)
    {
        // 从Cookie中获取ssid
        std::string cookie_str = conn->get_request_header("Cookie");
        if (cookie_str.empty())
        {
            DLOG("找不到cookie信息！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到cookie信息，请重新登录！");
        }
        std::string ssid_str;
        bool ret = get_cookie_val(cookie_str, "SSID", ssid_str);
        if (ret == false)
        {
            DLOG("找不到ssid信息！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到ssid信息，请重新登录！");
        }
        // 在session管理中查找会话信息
        session_ptr ssp = _sm.get_session_by_ssid(std::stol(ssid_str));
        if (ssp.get() == nullptr)
        {
            DLOG("找不到session，需要重新登录！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到session信息，请重新登录！");
        }
        // 从数据库中取出信息，序列化发送给客户端
        uint64_t uid = ssp->get_user();
        Json::Value user_info;
        ret = _ut.select_by_id(uid, user_info);
        if (ret == false)
        {
            DLOG("获取用户信息失败！");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到用户信息，请重新登录！");
        }
        std::string body;
        json_util::serialize(user_info, body);
        conn->set_body(body);
        conn->append_header("Content-Type", "application/json");
        conn->set_status(websocketpp::http::status_code::ok);
        // 刷新session过期时间
        _sm.set_session_expire_time(ssp->ssid(), SESSION_TIMEOUT);
    }
    // 处理普通的http请求
    void http_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string method = req.get_method();
        std::string uri = req.get_uri();
        if (method == "POST" && uri == "/reg")
            return reg(conn);
        else if (method == "POST" && uri == "/login")
            return login(conn);
        else if (method == "GET" && uri == "/info")
            return info(conn);
        else
            return file_handler(conn);
    }
    void ws_resp(wsserver_t::connection_ptr conn, Json::Value& resp)
    {
        std::string body;
        json_util::serialize(resp, body);
        conn->send(body);
    }
    session_ptr get_session_by_cookie(wsserver_t::connection_ptr conn)
    {
        Json::Value err_resp;
        // 从Cookie中获取ssid
        std::string cookie_str = conn->get_request_header("Cookie");
        if (cookie_str.empty())
        {
            err_resp["optype"] = "hall_ready";
            err_resp["reason"] = "找不到cookie信息，请重新登录！";
            err_resp["result"] = false;
            ws_resp(conn, err_resp);
            return session_ptr();
        }
        std::string ssid_str;
        bool ret = get_cookie_val(cookie_str, "SSID", ssid_str);
        if (ret == false)
        {
            err_resp["optype"] = "hall_ready";
            err_resp["reason"] = "找不到ssid信息，请重新登录！";
            err_resp["result"] = false;
            ws_resp(conn, err_resp);
            return session_ptr();
        }
        // 在session管理中查找会话信息
        session_ptr ssp = _sm.get_session_by_ssid(std::stol(ssid_str));
        if (ssp.get() == nullptr)
        {
            err_resp["optype"] = "hall_ready";
            err_resp["reason"] = "找不到session信息，请重新登录！";
            err_resp["result"] = false;
            ws_resp(conn, err_resp);
            return session_ptr();
        }
        return ssp;
    }
    void wsopen_game_hall(wsserver_t::connection_ptr conn)
    {
        Json::Value resp_json;
        // 获取客户端session
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr) return;
        // 判断当前客户端是否重复登录（已经在游戏大厅），加入游戏大厅
        if (_om.is_in_game_hall(ssp->get_user()) || _om.is_in_game_room(ssp->get_user()))
        {
            resp_json["optype"] = "hall_ready";
            resp_json["reason"] = "玩家重复登录！";
            resp_json["result"] = false;
            return ws_resp(conn, resp_json);
        }
        _om.enter_game_hall(ssp->get_user(), conn);
        // 响应客户端
        resp_json["optype"] = "hall_ready";
        resp_json["result"] = true;
        ws_resp(conn, resp_json);
        // 将session设置为永久存在
        _sm.set_session_expire_time(ssp->ssid(), SESSION_FOREVER);
    }
    void wsopen_game_room(wsserver_t::connection_ptr conn)
    {
        Json::Value resp_json;
        // 获取客户端session
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr) return;
        // 判断当前用户是否重复登录
        if (_om.is_in_game_hall(ssp->get_user()) || _om.is_in_game_room(ssp->get_user()))
        {
            resp_json["optype"] = "room_ready";
            resp_json["reason"] = "玩家重复登录！";
            resp_json["result"] = false;
            return ws_resp(conn, resp_json);
        }
        // 判断当前用户是否已经创建好房间
        room_ptr rp = _rm.get_room_by_uid(ssp->get_user());
        if (rp.get() == nullptr)
        {
            resp_json["optype"] = "room_ready";
            resp_json["reason"] = "没有找到玩家的房间信息！";
            resp_json["result"] = false;
            return ws_resp(conn, resp_json);
        }
        // 将当前用户添加到用户管理的游戏房间中
        _om.enter_game_room(ssp->get_user(), conn);
        // 将session设置为永久存在
        _sm.set_session_expire_time(ssp->ssid(), SESSION_FOREVER);
        
        resp_json["optype"] = "room_ready";
        resp_json["result"] = true;
        resp_json["room_id"] = rp->room_id();
        resp_json["uid"] = ssp->get_user();
        resp_json["white_id"] = rp->get_white_user();
        resp_json["black_id"] = rp->get_black_user();
        return ws_resp(conn, resp_json);
    }
    // websocket握手成功后进入长连接
    void wsopen_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            // 建立游戏大厅长连接
            wsopen_game_hall(conn);
        }
        else if (uri == "/room")
        {
            // 建立游戏房间长连接
            wsopen_game_room(conn);
        }
    }
    void wsclose_game_hall(wsserver_t::connection_ptr conn)
    {
        // 获取会话信息
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr) return;
        // 将玩家从游戏大厅中移除
        _om.exit_game_hall(ssp->get_user());
        // 将session恢复生命周期管理
        _sm.set_session_expire_time(ssp->ssid(), SESSION_TIMEOUT);
    }
    void wsclose_room_hall(wsserver_t::connection_ptr conn)
    {
        // 获取会话信息
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr) return;
        // 将玩家从游戏大厅中移除
        _om.exit_game_room(ssp->get_user());
        // 将session恢复生命周期管理
        _sm.set_session_expire_time(ssp->ssid(), SESSION_TIMEOUT);
        // 将玩家从游戏房间中移除
        _rm.remove_room_user(ssp->get_user());
    }
    // 连接断开
    void wsclose_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            // 游戏大厅
            wsclose_game_hall(conn);
        }
        else if (uri == "/room")
        {
            // 游戏房间
            wsclose_room_hall(conn);
        }
    }
    void wsmsg_game_hall(wsserver_t::connection_ptr conn, wsserver_t::message_ptr msg)
    {
        Json::Value resp_json;
        // 身份验证当前客户端是哪个玩家
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr) return;
        // 获取信息
        std::string req_body = msg->get_payload();
        Json::Value req_json;
        bool ret = json_util::unserialize(req_body, req_json);
        if (ret == false)
        {
            resp_json["result"] = false;
            resp_json["reason"] = "请求解析失败！";
            return ws_resp(conn, resp_json);
        }
        // 处理请求：开始匹配/停止匹配
        if (!req_json["optype"].isNull() && req_json["optype"].asString() == "match_start")
        {
            _mm.add(ssp->get_user());
            resp_json["optype"] = "match_start";
            resp_json["result"] = true;
            return ws_resp(conn, resp_json);
        }
        else if (!req_json["optype"].isNull() && req_json["optype"].asString() == "match_stop")
        {
            _mm.del(ssp->get_user());
            resp_json["optype"] = "match_stop";
            resp_json["result"] = true;
            return ws_resp(conn, resp_json);
        }
        resp_json["optype"] = "unknow";
        resp_json["reason"] = "请求类型未知";
        resp_json["result"] = false;
        return ws_resp(conn, resp_json);
    }
    void wsmsg_game_room(wsserver_t::connection_ptr conn, wsserver_t::message_ptr msg)
    {
        Json::Value resp_json;
        // 获取session信息
        session_ptr ssp = get_session_by_cookie(conn);
        if (ssp.get() == nullptr)
        {
            DLOG("房间-没有找到会话信息！");
            return;
        }
        // 获取房间信息
        room_ptr rp = _rm.get_room_by_uid(ssp->get_user());
        if (rp.get() == nullptr)
        {
            resp_json["optype"] = "unknow";
            resp_json["reason"] = "没有找到玩家的房间信息！";
            resp_json["result"] = false;
            DLOG("房间-没有找到玩家的房间信息！");
            return ws_resp(conn, resp_json);
        }
        // 反序列化
        Json::Value req_json;
        std::string req_body = msg->get_payload();
        bool ret = json_util::unserialize(req_body, req_json);
        if (ret == false)
        {
            resp_json["optype"] = "unknow";
            resp_json["reason"] = "请求解析失败！";
            resp_json["result"] = false;
            DLOG("房间-请求解析失败！");
            return ws_resp(conn, resp_json);
        }
        DLOG("房间-收到房间请求，开始处理");
        // 处理请求
        return rp->handle_request(req_json);
    }
    // 收到一条完整的websocket消息触发
    void wsmsg_callback(websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            // 游戏大厅
            wsmsg_game_hall(conn, msg);
        }
        else if (uri == "/room")
        {
            // 游戏房间
            wsmsg_game_room(conn, msg);
        }
    }
public:
    gobang_server(const std::string& host,
    const std::string& username,
    const std::string& password,
    const std::string& dbname,
    uint16_t port = 3306,
    const std::string& wwwroot = WWWROOT)
    :_web_root(wwwroot), _ut(host, username, password, dbname, port)
    ,_rm(&_ut, &_om), _sm(&_wssrv), _mm(&_rm, &_ut, &_om)
    {
        // 设置日志等级
        _wssrv.set_access_channels(websocketpp::log::alevel::none);
        // 初始化asio调度器
        _wssrv.init_asio();
        _wssrv.set_reuse_addr(true);
        // 设置回调函数
        _wssrv.set_http_handler(std::bind(&gobang_server::http_callback, this, std::placeholders::_1));
        _wssrv.set_open_handler(std::bind(&gobang_server::wsopen_callback, this, std::placeholders::_1));
        _wssrv.set_close_handler(std::bind(&gobang_server::wsclose_callback, this, std::placeholders::_1));
        _wssrv.set_message_handler(std::bind(&gobang_server::wsmsg_callback, this, std::placeholders::_1, std::placeholders::_2));
    }
    void start(int port)
    {
        // 监听端口
        _wssrv.listen(port);
        // 获取新连接
        _wssrv.start_accept();
        // 启动服务器
        _wssrv.run();
    }
private:
    std::string _web_root; // 静态资源根目录
    wsserver_t _wssrv; // server对象
    user_table _ut;
    online_manager _om;
    room_manager _rm;
    session_manager _sm;
    matcher_manager _mm;
};

#endif
